package com.example.servlet;


import com.alibaba.fastjson.JSON;
import com.example.dao.UserDao;
import com.example.dao.imp.UserDaoImp;
import com.example.domain.Users;
import com.example.utils.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.List;

@WebServlet(name = "UserServlet", value = "/userServlet")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2,  // 2 MB
        maxFileSize = 1024 * 1024 * 10,       // 10 MB
        maxRequestSize = 1024 * 1024 * 50     // 50 MB
)
public class UserServlet extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String userId = request.getParameter("userId");
        UserDao userDao = new UserDaoImp();
        if (username != null && !username.isEmpty()) {
            // 如果用户名不为空，则执行模糊搜索
            List<Users> userList = userDao.searchUsersByUsername(username);
            ResponseUtil.sendSuccessResponse(response, 200, userList);
        } else if (userId != null && ! userId.isEmpty()) {
            Users users = userDao.getUsersByUserId(Integer.parseInt(userId));
            ResponseUtil.sendSuccessResponse(response, 200, users);
        } else {
            // 如果用户名为空，则获取所有用户列表
            List<Users> userList = userDao.getAllUsers();
            request.setAttribute("operationType", "user");
            ResponseUtil.sendSuccessResponse(response, 200, userList);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 判断请求类型
        String contentType = request.getContentType();
        if (contentType != null && contentType.startsWith("multipart/form-data")) {
            // 处理文件上传
            handleFileUpload(request, response);
        } else if (contentType != null && contentType.startsWith("application/json")) {
            // 处理更新用户信息
            handleUpdateUserInfo(request, response);
        } else {
            // 不支持的请求类型
            ResponseUtil.sendErrorResponse(response, 400, "不支持的请求类型");
        }
    }

    //处理文件上传
    private void handleFileUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 获取当前项目的根目录路径
        String appPath = request.getServletContext().getRealPath("");
        // 确定上传文件存储的相对路径
        String relativePath = File.separator + "img"; // 暂时放在out目录下的webApp/img
        String absolutePath = appPath + relativePath;
        // 创建存储文件的目录
        File uploadDir = new File(absolutePath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        Part filePart = request.getPart("avatarFile");
        if (filePart != null && filePart.getSize() > 0) {
            String fileName = getFileName(filePart);
            InputStream fileContent = filePart.getInputStream();
            File file = new File(absolutePath + File.separator + fileName);
            try (FileOutputStream out = new FileOutputStream(file)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fileContent.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                // 返回头像文件的存储路径给前端
                String avatarUrl = "/img/" + fileName;
                ResponseUtil.sendSuccessResponse(response, 200, avatarUrl);
            }
        } else {
            ResponseUtil.sendErrorResponse(response, 400, "未选择文件或文件为空");
        }
    }
    // 处理更新用户信息
    private void handleUpdateUserInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BufferedReader reader = request.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        reader.close();

        // 解析 JSON 数据
        Users user = JSON.parseObject(jsonBuilder.toString(), Users.class);

        // 更新用户信息
        UserDao userDao = new UserDaoImp();
        userDao.updateUser(user); // 执行更新操作，根据实际情况调整

        ResponseUtil.sendSuccessResponse(response, 200, "用户信息更新成功");
    }
    private String getFileName(Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }


    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("data" + request.getParameter("data"));
        String id = request.getParameter("id");
        int userId = Integer.parseInt(id);
        UserDao userDao = new UserDaoImp();
        userDao.deleteUser(userId);
        ResponseUtil.sendSuccessResponse(response, 200, "用户删除成功");
        }

}
